import {ImageBackground, RefreshControl, ScrollView, View} from 'react-native';
import {Button, Card, Cell, Text, useAppTheme} from 'tsun-smart-ui';
import {useTranslation} from 'react-i18next';
import InfoCard from '@/components/DeviceInfo/DeviceInfoCard';
import {useHeaderHeight} from '@react-navigation/elements';
import Network from '@/assets/icon/network-installer.svg';
import {useNavigation} from '@react-navigation/native';
import {stationApi} from '@/services/api/stationApi';
import MemoLineChart from '@/components/LineChart';
import dayjs from 'dayjs';
import Logo from '@/components/Logo';
import DeviceSkeleton from '@/components/DeviceList/DeviceSkeleton';
import {useQuery} from '@tanstack/react-query';
import {StatisticsOptions} from '@/enums/statistics';
import { useStatisticsPicker } from '@/hooks/usePicker';

const Overview = () => {
  const {t} = useTranslation();
  const headerHeight = useHeaderHeight();
  const theme = useAppTheme();
  const navigation = useNavigation();
  const [picker, timeUnitCode] = useStatisticsPicker();
  const {data, refetch, isFetching, isLoading, isSuccess, error} = useQuery({
    queryKey: ['installer', 'scene', 'overview', timeUnitCode],
    queryFn: async () => {
      const {data} = await stationApi.getInstallerSceneOverview({
        grain: StatisticsOptions[timeUnitCode],
        year: dayjs().get('year'),
        month:
          timeUnitCode === 'sys.app.month' ? dayjs().get('month') + 1 : void 0,
      });
      return data;
    },
  });
  if (isLoading) {
    return (
      <DeviceSkeleton className="px-4" style={{marginTop: headerHeight}} />
    );
  }
  if (error) throw new Error(error.message);
  if (isSuccess)
    return (
      <ImageBackground
        source={!theme.isDark ? require('@/assets/imgs/Background.png') : null}
        imageStyle={{
          height: 402,
        }}>
        <ScrollView
          className="px-4"
          showsVerticalScrollIndicator={false}
          style={{
            marginTop: headerHeight,
          }}
          refreshControl={
            <RefreshControl refreshing={isFetching} onRefresh={refetch} />
          }
          contentContainerClassName="gap-y-3">
          <InfoCard
            items={[
              {
                label: t('monitor.tab.title.configuring'),
                value: data.toConfigureStationCount,
              },
              {
                label: t('monitor.tab.title.installing'),
                value: data.toInstallStationCount,
              },
            ]}
            right={
              <Text variant="navTitle" className=" font-heading">
                {data.stationCount}
              </Text>
            }
            title={
              <View className="flex-row items-center">
                <Logo
                  name="installer-power"
                  round={false}
                  backgroundColor={theme.colors?.brand?.primaryLight!}
                  color={theme.colors?.brand?.primary!}
                />
                <Text variant="bodyStrong" className="ml-2">
                  {`${t('monitor.stat')}${t('device.totalNumber')}`}
                </Text>
              </View>
            }></InfoCard>
          <InfoCard
            items={[
              {
                label: t('job.status.Normal', {
                  defaultValue: '正常',
                }),
                value: data.normalDeviceCount,
              },
              {
                label: t('monitor.tab.title.offline', {
                  defaultValue: '离线',
                }),
                value: data.offlineDeviceCount,
              },
              {
                label: t('user.alarm', {
                  defaultValue: '告警',
                }),
                value: data.faultDeviceCount,
              },
            ]}
            right={
              <Text variant="navTitle" className=" font-heading">
                {data.deviceCount}
              </Text>
            }
            title={
              <View className="flex-row items-center">
                <Logo
                  name="equipment"
                  round={false}
                  backgroundColor={theme.colors?.info?.light!}
                  color={theme.colors?.info?.primary!}
                />
                <Text variant="bodyStrong" className="ml-2">
                  {t('device.equipment') +
                    t('device.totalNumber', {defaultValue: '总设备'})}
                </Text>
              </View>
            }></InfoCard>
          <Card
            title={t('workplace.totalInstalledCap')}
            right={
              <Button
                variant="text"
                style={{
                  flexDirection: 'row-reverse',
                }}
                onPress={() => {
                  picker.show();
                }}
                title={t(timeUnitCode)}
                size="small"
                icon={'pull'}></Button>
            }>
            <View
              className="mt-4 w-full"
              style={{
                aspectRatio: 2 / 1,
              }}>
              <MemoLineChart
                chartData={[
                  data.installTrendList.map(item => item.installCount),
                ]}
                xAxisLabels={data.installTrendList.map(item => item.time)}
                showLegend={false}
                marker={`${t('sys.app.time')}: `}
                yAxis={{
                  left: {
                    drawAxisLine: false,
                  },
                }}
                scaleYEnabled={false}
              />
            </View>
          </Card>
          <Cell
            data={[
              {
                title: t('common.networkTool', {
                  defaultValue: '配网工具',
                }),
                left: size => (
                  <Network
                    color={theme.colors?.brand?.primary}
                    width={size}
                    height={size}></Network>
                ),
                onPress: () => {
                  navigation.navigate('Scan', {
                    setupNetworkOnly: true,
                  });
                },
              },
            ]}></Cell>
        </ScrollView>
      </ImageBackground>
    );
};
export default Overview;
